﻿


CREATE PROCEDURE [dbo].[proc_App_Menu_Create]
	(		
		@Mid varchar(100),
		@Mname nvarchar(50),
		@Mpath varchar(100),
		@Msort INT,
		@Mark  INT,
		@EntryPeople varchar(50)			
	)
AS
	declare @Mid_tem varchar(100)
	declare @Mid_temp varchar(100)
	BEGIN	
	IF(@Mid='0')
	SET @Mid_tem=(SELECT top(1) mid FROM [App_Menu] WHERE LEN(mid)<3  ORDER BY mid DESC)
	ELSE IF(SUBSTRING(@Mid,LEN(@Mid),1)='A')
	SET @Mid_tem=(SELECT top(1) mid FROM [App_Menu] WHERE LEN(mid)<5 AND LEN(mid)>2 AND SUBSTRING(mid,1,2)=SUBSTRING(@Mid,1,2) ORDER BY mid DESC)
	ELSE IF(SUBSTRING(@Mid,LEN(@Mid),1)='B')
	SET @Mid_tem=(SELECT top(1) mid FROM [App_Menu] WHERE LEN(mid)>5 AND LEN(mid)<7 AND SUBSTRING(mid,1,4)=SUBSTRING(@Mid,1,4)  ORDER BY mid DESC)	
	ELSE IF(SUBSTRING(@Mid,LEN(@Mid),1)='C')
	SET @Mid_tem=(SELECT top(1) mid FROM [App_Menu] WHERE LEN(mid)>7 AND SUBSTRING(mid,1,6)=SUBSTRING(@Mid,1,6) ORDER BY mid DESC)		
	END
	
	IF(@Mid_tem='' OR @Mid_tem IS NULL)	
	BEGIN
		IF(LEN(@Mid)<2)	
		SET @Mid_temp='01'
		ELSE SET @Mid_temp=SUBSTRING(@Mid,1,LEN(@Mid)-1)+'01'
	END 
	
	ELSE 
	BEGIN		
		declare @Mid_tt varchar(100)
		set @Mid_tt=CAST(CONVERT(int,SUBSTRING(@Mid_tem,LEN(@Mid_tem)-1,2)+1) AS VARCHAR(10))
		
		IF(LEN(@Mid_tt)=1)
		SET @Mid_tt='0'+@Mid_tt
		
		IF(len(@Mid_tem)=2)
		SET @Mid_temp=@Mid_tt
		ELSE
	    SET @Mid_temp=SUBSTRING(@Mid_tem,1,LEN(@Mid_tem)-2)+@Mid_tt		
	END
	declare @ename NVARCHAR(20)
	set @ename = (SELECT EName FROM Employee WHERE UserName=@EntryPeople)
	IF(@ename is NULL)
	set @ename=@EntryPeople
	INSERT INTO App_Menu (MID,MName,MPath,Msort,MARK,EntryPeople) Values(@Mid_temp,@Mname,@Mpath,@Msort,@Mark,@ename)
	RETURN



